package org.javaforever.cookieshop.serviceimpl;

import java.util.List;
import org.javaforever.cookieshop.dao.RecommendDao;
import org.javaforever.cookieshop.domain.RecommendBean;
import org.javaforever.cookieshop.service.RecommendService;
import org.javaforever.cookieshop.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;

@Service
public class RecommendServiceImpl implements RecommendService{
	@Autowired
	protected RecommendDao dao;

	@PersistenceContext
	protected EntityManager entityManager;

	@Override
	public void activateAllRecommends(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.activateRecommend(id);
        }
	}

	@Override
	public Boolean activateRecommend(Long id) throws Exception{
        dao.activateRecommend(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean addRecommend(RecommendBean recommend) throws Exception{
        dao.saveAndFlush(recommend);
        return true;
	}

	@Override
	public void cloneAllRecommends(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            cloneRecommend(id);
        }
	}

	@Override
	public Boolean cloneRecommend(Long id) throws Exception{
        RecommendBean recommend = dao.findRecommendFullInfoById(id);
        
        String name = recommend.getName();
        String shortName = name;
        if (name.contains("_") && StringUtil.isInteger(name.substring(name.lastIndexOf('_')+1,name.length()))) {
            shortName = name.substring(0,name.lastIndexOf('_'));
        }
        List<RecommendBean> names = dao.searchRecommendIndexedNamesByShortName(shortName);
        int indexNum = 1;
        for (RecommendBean recommend0:names) {
            String _name = recommend0.getName();
            if (_name.contains("_") && StringUtil.isInteger(_name.substring(_name.lastIndexOf('_')+1,_name.length()))) {
                int index = Integer.valueOf(_name.substring(_name.lastIndexOf('_')+1,_name.length()));
                if (index >= indexNum) {
                    indexNum = index + 1;
                }
            }
        }
        String indexName = shortName + "_" + indexNum;
        RecommendBean recommend1 = recommend.clone();
        recommend1.setId(null);
        recommend1.setName(indexName);
        addRecommend(recommend1);
        return true;
	}

	@Override
	public Integer countActiveRecommendRecords() throws Exception{
        return dao.countActiveRecommendRecords();
	}

	@Override
	public Integer countSearchRecommendsByFieldsRecords(RecommendBean recommend) throws Exception{
        String jpql = "select count(*) as countNum from RecommendBean r where 1=1 ";
        if (recommend.getName() != null) {
            jpql += " and r.name like CONCAT('%', '"+recommend.getName()+"','%')";
        }
        if (recommend.getActive() != null) {
            jpql += " and r.active = "+recommend.getActive();
        }
        if (recommend.getType() != null) {
            jpql += " and r.type = "+recommend.getType();
        }
        if (recommend.getGoods() != null) {
            jpql += " and r.goods = "+recommend.getGoods();
        }
        Query query = entityManager.createQuery(jpql);
        Long count = (Long) query.getSingleResult();
        return count.intValue();
	}

	@Override
	public void deleteAllRecommends(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.deleteRecommend(id);
        }
	}

	@Override
	public Boolean deleteRecommend(Long id) throws Exception{
        dao.deleteRecommend(id);
        return true;
	}

	@Override
	public RecommendBean findRecommendById(Long id) throws Exception{
        return dao.findRecommendById(id);
	}

	@Override
	public RecommendBean findRecommendByName(String name) throws Exception{
        return dao.findRecommendByName(name);
	}

	@Override
	public List<RecommendBean> listActiveRecommends() throws Exception{
        return dao.listActiveRecommends();
	}

	@Override
	public List<RecommendBean> listAllRecommends() throws Exception{
        return dao.listAllRecommends();
	}

	@Override
	public List<RecommendBean> searchRecommendsByFields(RecommendBean recommend) throws Exception{
        String jpql = "from RecommendBean r where 1=1 ";
        if (recommend.getName() != null) {
            jpql += " and r.name like CONCAT('%', '"+recommend.getName()+"','%')";
        }
        if (recommend.getActive() != null) {
            jpql += " and r.active = "+recommend.getActive();
        }
        if (recommend.getType() != null) {
            jpql += " and r.type = "+recommend.getType();
        }
        if (recommend.getGoods() != null) {
            jpql += " and r.goods = "+recommend.getGoods();
        }
        Query query = entityManager.createQuery(jpql);
        List<RecommendBean> results = query.getResultList();
        return results;
	}

	@Override
	public List<RecommendBean> searchRecommendsByFieldsByPage(RecommendBean recommend,Integer pagesize,Integer pagenum) throws Exception{
        Integer start = (pagenum-1)*pagesize;
        Integer limit = pagesize;
        String jpql = "from RecommendBean r where 1=1 ";
        if (recommend.getName() != null) {
            jpql += " and r.name like CONCAT('%', '"+recommend.getName()+"','%')";
        }
        if (recommend.getActive() != null) {
            jpql += " and r.active = "+recommend.getActive();
        }
        if (recommend.getType() != null) {
            jpql += " and r.type = "+recommend.getType();
        }
        if (recommend.getGoods() != null) {
            jpql += " and r.goods = "+recommend.getGoods();
        }
        Query query = entityManager.createQuery(jpql);
        query.setFirstResult(start); // 设置起始位置
        query.setMaxResults(limit); // 设置返回结果数量
        List<RecommendBean> results = query.getResultList();
        return results;
	}

	public void setDao(RecommendDao dao){
		this.dao = dao;
	}

	@Override
	public void softDeleteAllRecommends(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.softDeleteRecommend(id);
        }
	}

	@Override
	public boolean softDeleteRecommend(Long id) throws Exception{
        dao.softDeleteRecommend(id);
        return true;
	}

	@Override
	public Boolean toggleOneRecommend(Long id) throws Exception{
        RecommendBean recommend = dao.findRecommendById(id);
        if (recommend.getActive()==false) {
            dao.toggleRecommend(id);
        }
        else {
            Integer count = dao.countActiveRecommendRecords();
            if (count > 1){
                dao.toggleRecommend(id);
            }
        }
        return true;
	}

	@Override
	public Boolean toggleRecommend(Long id) throws Exception{
        dao.toggleRecommend(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean updateRecommend(RecommendBean recommend) throws Exception{
        entityManager.merge(recommend);
        return true;
	}

}
